package com.shiku.imserver.common.utils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class HttpParseUtils {
    private static ConcurrentHashMap<Integer, Pattern> regexPattern = new ConcurrentHashMap<>();

    private static Pattern getCachedPattern(String regex) {
        if (regexPattern.containsKey(Integer.valueOf(regex.hashCode()))) {
            return regexPattern.get(Integer.valueOf(regex.hashCode()));
        }
        Pattern pattern = Pattern.compile(regex);
        regexPattern.put(Integer.valueOf(regex.hashCode()), pattern);
        return pattern;
    }

    public static Map<String, String> getEqualMap(String str) {
        Map<String, String> equalMap = new HashMap<>();
        String[] searchedStrings = searchByRegex(str, "([^ ;,]+=[^ ;,]+)");
        for (String groupString : searchedStrings) {
            int equalCharIndex = groupString.indexOf("=");
            String[] equalStrings = {groupString.substring(0, equalCharIndex), groupString.substring(equalCharIndex + 1, groupString.length())};
            if (equalStrings.length == 2) {
                String key = equalStrings[0];
                String value = equalStrings[1];
                if (value.startsWith("\"") && value.endsWith("\"")) {
                    value = value.substring(1, value.length() - 1);
                }
                equalMap.put(key, value);
            }
        }
        return equalMap;
    }

    public static String getPerprotyEqualValue(Map<String, String> packetMap, String propertyName, String valueName) {
        String propertyValueObj = packetMap.get(propertyName);
        if (propertyValueObj == null) {
            return null;
        }
        return getEqualMap(propertyValueObj.toString()).get(valueName);
    }

    public static void main(String[] args) {
    }

    public static String[] searchByRegex(String source, String regex) {
        if (source == null) {
            return null;
        }
        Matcher matcher = getCachedPattern(regex).matcher(source);
        ArrayList<String> result = new ArrayList<>();
        while (matcher.find()) {
            result.add(matcher.group());
        }
        return (String[]) result.toArray(new String[0]);
    }
}
